package zhengfuzhe.com.newupload1.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.io.File;

import de.greenrobot.event.EventBus;
import zhengfuzhe.com.newupload1.PreferenceUtils;
import zhengfuzhe.com.newupload1.busMessager.MyInstalledMessage;
import zhengfuzhe.com.newupload1.download.DownloadInfo;
import zhengfuzhe.com.newupload1.download.DownloadManager;

public class MyReceiver extends BroadcastReceiver {
    public MyReceiver() {
    }

    private final static String TAG = "MyBroadCastReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e(TAG, "----收到广播-----");
        if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) {
            Log.e(TAG, "package has been added");
            String packageName = intent.getData().getSchemeSpecificPart();
            //通过包名获取文件名称
            String label = PreferenceUtils.getString(context.getApplicationContext(), packageName);
            //通过文件名称获取文件存储路径
            String fileSavePath = PreferenceUtils.getString(context.getApplicationContext(), label);
            if (fileSavePath != null) {
                //获取数据库管理者
                DbManager db = DownloadManager.getInstance().getDb();
                try {
                    //通过文件名称和存储路径获取对象
                    DownloadInfo downloadInfo = db.selector(DownloadInfo.class)
                            .where("label", "=", label)
                            .and("fileSavePath", "=", fileSavePath)
                            .findFirst();
                    //将获取的对象从数据库中移除
                    DownloadManager.getInstance().removeDownload(downloadInfo);
                } catch (DbException e) {
                    e.printStackTrace();
                }
                Log.e(TAG, "----文件label----string----" + label);
                Log.e(TAG, "----文件fileSavePath----string----" + fileSavePath);
                //安装完成功之后，删除文件
                File file = new File(fileSavePath);
                file.delete();
                //发送消息给DownloadActivity,说经已经安装完成，将已经完成的文件名和包名发送过去
                EventBus.getDefault().post(new MyInstalledMessage(true, packageName));//安装完成后发送消息
                Toast.makeText(context, "安装已完成，安装包已删除", Toast.LENGTH_SHORT).show();//提示用安装完成后删除安装包，节约资源
            }

            Log.e(TAG, "----收到广播--getSchemeSpecificPart---" + packageName);
        } else if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")) {
            Log.e(TAG, "package has been removed");
        }
    }
}